import mqtt from 'mqtt/dist/mqtt.js'
import {api} from './api.js'
let client;
class mqttUtil{
	constructor(){
		this.mqtt_option={
		 connectTimeout:5000,
			clientId:'jwhjwh_main',
			clean:false
		}
		this.topic=['can2android','android2can']
	}
	connect(){
		let that=this
		let host=""
		// #ifdef H5
		host="ws://"+api.mqttUrl
		// #endif
		// #ifdef APP||APP-PLUS
		host="wx://"+api.mqttUrl
		// #endif
		if(client==null||client.connect==false){
			client=mqtt.connect(host,this.mqtt_option)
			client.on('connect',(topic,message)=>{
				console.log('连接成功')
				client.subscribe(that.topic,err=>{
					if(!err){
						console.log('订阅成功');
					}
				})
			})
		}
		client.on("message",(topic,message)=>{
			let data1={topic:topic,data:message.toString()}
			uni.$emit(`update_${topic}`,message)
			uni.$emit(`update`,data1)
		})
		client.on("reconnect",e=>{
			uni.showToast({
				title:'mqtt正在重连',
				icon:'error'
			})
			console.log('正在重连');
		})
		client.on('err',err=>{
			console.log('连接失败');
		})
		client.on('end',err=>{
			console.log('连接断开');
		})
		
	}
	sendMes(topic,mes){
		client.publish(topic,mes)
	}
}export default mqttUtil